package util

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net"
	"time"
)

func LoadConf(relativePath string) []byte {
	f, err := ioutil.ReadFile(relativePath)
	if err != nil {
		fmt.Println("read fail", err)
	}
	return f
}

func LoadConfAndUnMarshal(relativePath string,target interface{}) {
	f, err := ioutil.ReadFile(relativePath)
	if err != nil {
		fmt.Println("read fail", err)
		return
	}
	err = json.Unmarshal(f, target)
	if err != nil {
		fmt.Println(err)
	}
}

func GetLogId() string {
	now := time.Now()
	r := rand.Int31n(10000)
	return fmt.Sprintf("%s%d%s%d",now.Format(TIMELAYOUTNO),now.UnixNano()/10e6,GetLocalIPStr(),r)
}

func GetLocalIPStr() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			to4 := ipnet.IP.To4()
			if to4 != nil {
				//192.168.56.1
				return fmt.Sprintf("%d%d%d%d",to4[0],to4[1],to4[2],to4[3])
			}
		}
	}
	return ""
}